package visiopuce.ui.providers;

import java.util.Calendar;
import java.util.Date;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DateTime;

public class DateCellEditor extends CellEditor {

	private Date value;

	private DateTime dateTime;

	/**
	 * Default TextCellEditor style specify no borders on text widget as cell
	 * outline in table already provides the look of a border.
	 */
	private static final int defaultStyle = SWT.DROP_DOWN;

	public DateCellEditor(Composite parent) {
		this(parent, defaultStyle);
	}

	/**
	 * 
	 * @param parent
	 * @param style
	 *            For different displays : <br/>
	 *            - SWT.BORDER<br/>
	 *            - SWT.DROPDOWN<br/>
	 *            For different format - SWT.DATE : Présentation de la date -
	 *            SWT.TIME : Présentation de l'heure - SWT.CALENDAR:
	 *            Présentation d'un calendrier Détails des differents formats
	 *            pour SWT. : <br/>
	 *            - SWT.SHORT : "Janvier 2012"<br/>
	 *            - SWT.MEDIUM (default) : 27/01/2012<br/>
	 *            - SWT.LONG : Vendredi 27 janvier 2012 <br/>
	 */
	public DateCellEditor(Composite parent, int style) {
		super(parent, style);
	}

	@Override
	protected Control createControl(Composite parent) {
		dateTime = new DateTime(parent, getStyle());

		return dateTime;
	}

	@Override
	public Object doGetValue() {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, dateTime.getYear());
		c.set(Calendar.MONTH, dateTime.getMonth());
		c.set(Calendar.DAY_OF_MONTH, dateTime.getDay());
		return c.getTime();
	}

	@Override
	protected void doSetFocus() {
		if (dateTime != null) {
			dateTime.setFocus();
		}
	}

	private void reset() {
		doSetValue(this.value);
	}

	@Override
	protected void doSetValue(Object value) {
		if (dateTime != null && (value instanceof Date)) {
			this.value = (Date) value;

			Calendar c = Calendar.getInstance();
			c.setTime(this.value);
			dateTime.setYear(c.get(Calendar.YEAR));
			dateTime.setMonth(c.get(Calendar.MONTH));
			dateTime.setDay(c.get(Calendar.DAY_OF_MONTH));
		}

	}

}
